package com.kla.power.scheduled;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.kla.power.entity.AlarmEntity;
import com.kla.power.entity.InverterElectricEntity;
import com.kla.power.service.IAlarmService;
import com.kla.power.service.IInverterElectricService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: Wuzh
 * @Description:
 * @Date Created in 23:03 2025-10-12
 * @return
 */
@Component
@EnableScheduling
@Slf4j
public class AlarmStatisticsScheduled {

    @Resource
    private IAlarmService iAlarmService;
    @Resource
    private IInverterElectricService iInverterElectricService;

    @Scheduled(cron = "0 30 23 * * ?")
    public void statisticsDay () {
        log.info ( "每天晚上11.30检索所有逆变器的异常信息，如果今天发生报警的逆变器今天有数据进来，都恢复." );
        LocalDateTime now = LocalDateTime.now ();
        LocalDateTime startOfDay = now.toLocalDate ().atStartOfDay (); // 今天 00:00:00
        LocalDateTime endOfDay = now.toLocalDate ().atTime ( LocalTime.MAX ); // 今天 23:59:59.999999999
        List<AlarmEntity> list = iAlarmService.list ( new LambdaQueryWrapper<AlarmEntity> ().eq ( AlarmEntity :: getStatus, 1 ).groupBy ( AlarmEntity :: getDeviceSn ) );
        if ( list != null && list.size () > 0 ) {
            // 说明今天还有报警没有自动恢复，检查这些逆变器今天有没有发电，如果今天有正常发电，则恢复
            List<String> deviceSns = list.stream ().map ( AlarmEntity :: getDeviceSn ).distinct ().collect ( Collectors.toList () );
            List<InverterElectricEntity> electricEntities = iInverterElectricService.list ( new LambdaQueryWrapper<InverterElectricEntity> ()
                                                                                                    .in ( InverterElectricEntity :: getSerialNumber, deviceSns )
                                                                                                    .ge ( InverterElectricEntity :: getCreateTime, startOfDay )
                                                                                                    .le ( InverterElectricEntity :: getCreateTime, endOfDay )
            );
            // 后续逻辑：根据 electricEntities 是否非空，决定是否恢复报警
            if ( electricEntities != null && electricEntities.size () > 0 ) {
                List<String> sns = electricEntities.stream ().map ( InverterElectricEntity :: getSerialNumber ).distinct ().collect ( Collectors.toList () );
                iAlarmService.update ( new LambdaUpdateWrapper<AlarmEntity> ().set ( AlarmEntity :: getStatus, 0 ).in ( AlarmEntity :: getDeviceSn, sns ) );
            }
        }
    }


}
